package com.cake.liulanxiangzhu.security;

import com.alibaba.fastjson.JSON;
import com.cake.liulanxiangzhu.exception.ServiceException;
import com.cake.liulanxiangzhu.mapper.AdminUserMapper;
import com.cake.liulanxiangzhu.pojo.vo.AdminUserVO;
import com.cake.liulanxiangzhu.utils.DataUseUtil;
import com.cake.liulanxiangzhu.web.JsonResult;
import com.cake.liulanxiangzhu.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import static com.cake.liulanxiangzhu.service.impl.AdminUserServiceImpl.LOGINSMS;

@Service
@Slf4j
public class SmsDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        log.debug("执行了短信验证");
        AdminUserVO adminUserVO = adminUserMapper.selectPermissionByPhone(phone);
        if (adminUserVO == null) {
            String message = "登录失败，用户名不存在！";
            throw new BadCredentialsException(message);
        }
        String code = (String) redisTemplate.opsForValue().get(LOGINSMS+phone);
        if (DataUseUtil.isNotBlank(code)){
            log.debug("验证码是{}",code);
            List<GrantedAuthority> authorities = new ArrayList<>();
            for (String permission : adminUserVO.getPermissions()) {
                GrantedAuthority authority = new SimpleGrantedAuthority(permission);
                authorities.add(authority);
            }
            AdminDetails adminDetails = new AdminDetails(adminUserVO.getPhone(),code,adminUserVO.getEnable()==1,authorities);
            adminDetails.setId(adminUserVO.getId());
            return adminDetails;
        }else {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"验证码已过期" );

        }
    }
}
